import logging
from fastapi import APIRouter, Query
from fastapi.exceptions import HTTPException
from tortoise.expressions import Q

from app.controllers.rotor import rotor_type_controller
from app.schemas.base import Success, SuccessExtra
from app.schemas.rotor import RotorTypeCreate, RotorTypeUpdate, RotorTypeList

logger = logging.getLogger(__name__)
router = APIRouter()


@router.get("/list", summary="获取旋翼类型列表")
async def get_rotor_type_list(
    page: int = Query(1, description="页码"),
    page_size: int = Query(10, description="每页数量"),
    name: str = Query("", description="旋翼类型名称，用于查询"),
):
    q = Q()
    if name:
        q = Q(name__contains=name)
    total, rotor_objs = await rotor_type_controller.list(page=page, page_size=page_size, search=q)
    data = [await obj.to_dict() for obj in rotor_objs]
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)


@router.get("/get", summary="查看旋翼类型")
async def get_rotor_type(
    rotor_type_id: int = Query(..., description="旋翼类型ID"),
):
    rotor_obj = await rotor_type_controller.get(id=rotor_type_id)
    return Success(data=await rotor_obj.to_dict())


@router.post("/create", summary="创建旋翼类型")
async def create_rotor_type(rotor_in: RotorTypeCreate):
    if await rotor_type_controller.is_exists(name=rotor_in.name):
        raise HTTPException(
            status_code=400,
            detail="The rotor type with this name already exists in the system.",
        )
    await rotor_type_controller.create(obj_in=rotor_in)
    return Success(msg="Created Successfully")


@router.post("/update", summary="更新旋翼类型")
async def update_rotor_type(rotor_in: RotorTypeUpdate):
    await rotor_type_controller.update(id=rotor_in.id, obj_in=rotor_in)
    return Success(msg="Updated Successfully")


@router.delete("/delete", summary="删除旋翼类型")
async def delete_rotor_type(
    rotor_type_id: int = Query(..., description="旋翼类型ID"),
):
    await rotor_type_controller.remove(id=rotor_type_id)
    return Success(msg="Deleted Successfully") 